package com.powervision.thirdlogindemo.utils

import android.app.Activity
import android.content.Intent
import com.twitter.sdk.android.core.Callback
import com.twitter.sdk.android.core.Twitter
import com.twitter.sdk.android.core.TwitterCore
import com.twitter.sdk.android.core.TwitterSession
import com.twitter.sdk.android.core.identity.TwitterAuthClient
import com.twitter.sdk.android.core.identity.TwitterLoginButton
import com.twitter.sdk.android.core.internal.CommonUtils
import java.lang.ref.WeakReference

/**
 * @auth: njb
 * @date: 2021/10/27 15:31
 * @desc: Twitter登录工具类
 */
class TwitterLoginUtils(activity: Activity) {
    private val mWeakReference by lazy { WeakReference(activity) }

    var callback: Callback<TwitterSession> ?= null

    @Volatile
    var authClient: TwitterAuthClient? = null

    init {
        Twitter.getInstance()
    }

    companion object{
        const val ERROR_MSG_NO_ACTIVITY = ("TwitterLoginButton requires an activity."
                + " Override getActivity to provide the activity for this button.")
    }

    fun setOnLoginByTwitterClick(callback: Callback<TwitterSession>?) {
        this.callback = callback
        checkCallback(callback)
        checkActivity(mWeakReference.get())
        twitterAuthClient?.authorize(mWeakReference.get(), callback)
    }

    private fun checkActivity(activity: Activity?) {
        if (activity == null || activity.isFinishing) {
            CommonUtils.logOrThrowIllegalStateException(TwitterCore.TAG, ERROR_MSG_NO_ACTIVITY)
        }
    }

    private fun checkCallback(callback: Callback<TwitterSession>?) {
        if(callback == null){
            CommonUtils.logOrThrowIllegalStateException(
                TwitterCore.TAG,
                "Callback must not be null, did you call setCallback?")
        }
    }

    private val twitterAuthClient: TwitterAuthClient?
        get() {
            if (authClient == null) {
                synchronized(TwitterLoginButton::class.java) {
                    if (authClient == null) {
                        authClient = TwitterAuthClient()
                    }
                }
            }
            return authClient
        }


    fun onActivityResult(requestCode:Int,resultCode:Int, data: Intent?){
        if (requestCode == twitterAuthClient?.requestCode) {
            twitterAuthClient?.onActivityResult(requestCode, resultCode, data)
        }
    }
}